import { createRouter, createWebHistory } from "vue-router";

const routes = [
  {
    path: "/",
    redirect: "/login",
  },
  {
    path: "/login",
    component: () => import("@/views/Login.vue"),
  },
  {
    path: "/home",
    name: "home",
    component: () => import("@/views/Home.vue"),
    redirect: "/welcome",
    children: [
      {
        path: "/welcome",
        component: () => import("@/views/Welcome.vue"),
      },
      {
        path: "/401",
        component: () => import("@/views/error/401.vue"),
      },
      // 强制刷新浏览器，此时，控制台会友好的提示：[Vue Router warn]: No match found for location with path ‘xxx’ 的警告
      // 只需要在公有的路由表最后添加段代码即可
      {
        path: "/:pathMatch(.*)*",
        component: () => import("@/views/error/404.vue"),
      },
    ],
  },
];

export const router = createRouter({
  history: createWebHistory(),
  routes,
});

// vite的路由组件转换
const comp = import.meta.glob("../views/**/Index.vue");

/**
 * 添加路由
 */
export function addMyRouters(myRouters) {
  // 是否有新路由
  let hasNewRoutes = false;
  myRouters.forEach((item) => {
    if (!router.hasRoute(item.path)) {
      hasNewRoutes = true;
      const currentRoute = {};
      // vite的路由组件转换
      currentRoute.component = comp[`../views${item.path}/Index.vue`];
      currentRoute.path = item.path;
      router.addRoute("home", currentRoute);
    }
  });
  return hasNewRoutes;
}
